package com.lyb.spzx.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.lyb.spzx.common.exception.DefinedException;
import com.lyb.spzx.model.entity.pay.PaymentInfo;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import com.lyb.spzx.pay.properties.AlipayProperties;
import com.lyb.spzx.pay.service.AlipayService;
import com.lyb.spzx.pay.service.PaymentInfoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    AlipayClient alipayClient;

    @Autowired
    AlipayProperties alipayProperties;

    @SneakyThrows
    @Override
    public String submitAlipay(String orderNo) {
        //保存支付记录
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);
        //创建API对应的request
        AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
        //同步回调
        alipayTradeWapPayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());
        //异步回调
        alipayTradeWapPayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        //准备参数，声明一个map集合
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no",paymentInfo.getOrderNo());
        map.put("product_code","QUICK_WAP_WAY");
//        map.put("total_amount",paymentInfo.getAmount());
        map.put("total_amount",new BigDecimal("0.01"));//先给个固定值，一分钱测试
        map.put("subject",paymentInfo.getContent());
        alipayTradeWapPayRequest.setBizContent(JSON.toJSONString(map));
        
        //发送请求
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayTradeWapPayRequest);
        if (response.isSuccess()){
            log.info("调用成功");
            return response.getBody();
        }else {
            log.info("调用失败");
            throw new DefinedException(ResultCodeEnum.DATA_ERROR);
        }

    }
}
